package models

import (
	"time"
	"hytx_manager/pkg/gredis"
	"strconv"
	"github.com/gin-gonic/gin"
)

type Spread struct {
	ID               int       `gorm:"primary_key" json:"id"`
	UserId           int       `json:"user_id"`
	MaibaoNum        int       `json:"maibao_num"`
	MaibaoNumSurplus int       `json:"maibao_num_surplus"`
	MaibaoSpendNum   int       `json:"maibao_spend_num"`
	Cover            string    `json:"cover"`
	Content          string    `json:"content"`
	Status           int       `json:"status"`
	UserMarketingId  int       `json:"user_marketing_id"`
	CardId           int       `json:"card_id"`
	ProvinceId       int       `json:"province_id"`
	BrowseNum        int       `json:"browse_num"`
	ShareNum         float64   `json:"share_num"`
	Remarks          string    `json:"remarks"`
	IsDeleted        int       `json:"is_deleted"`
	CreatedAt        time.Time `json:"created_at"`
	UpdatedAt        time.Time `json:"updated_at"`
}

func (a *Spread) TableName() string {
	return "spread"
}

type SpreadResult struct {
	ID              int       `json:"id"`
	Account         string    `json:"account"`
	UsersName       string    `json:"users_name"`
	Company         string    `json:"company"`
	Title           string    `json:"title"`
	Cover           string    `json:"cover"`
	Type            int 	  `json:"type"`
	Content         string    `json:"content"`
	MaibaoNum       int       `json:"maibao_num"`
	MaibaoSpendNum  int       `json:"maibao_spend_num"`
	ShareNum        float64   `json:"share_num"`
	Province        string    `json:"province"`
	Status          int       `json:"status"`
	CardId          int       `json:"card_id"`
	CardHeadPicture string    `json:"card_head_picture"`
	CreatedAt       time.Time `json:"created_at"`
}

//todo 查看

func GetSpreadResultMemberList(page int, pageSize int, c *gin.Context) ([]*SpreadResult, *Paginator) {
	var data []*SpreadResult
	item := DB.Table("spread as t1").Select("t1.id, t1.title, t1.type, t2.user_name, t2.mobile_phone as account, t1.cover, t1.maibao_num, t1.maibao_spend_num, t1.content, t1.status, t1.created_at, t3.name as province, t1.maibao_num_surplus / t1.maibao_spend_num as share_num,t2.id as card_id, t2.head_picture as card_head_picture").Joins("left join cards as t2 on t1.user_id = t2.user_id").Joins("left join places as t3 on  t1.province_id = t3.id").Where("is_deleted=0").Where("t1.status<>4").Where("t1.type=0").Order("created_at desc")

	if name := c.Query("name"); name != "" {
		item.Where("t2.user_name like ? or t2.mobile_phone like", "%"+name+"%", "%"+name+"%")
	}
	if status := c.Query("status"); status != ""{
		item.Where("t1.status=?",status)
	}
	if title := c.Query("title"); title != "" {
		item = item.Where("t1.title like ? ", "%"+title+"%")
	}
	if begin_time := c.Query("begin_time"); begin_time != "" {
		item = item.Where("t1.created_at > ?", begin_time)
	}
	if end_time := c.Query("end_time"); end_time != "" {
		item = item.Where("t1.created_at < ?", end_time)
	}
	var count int
	item.Count(&count)
	paginate := NewPage(page, pageSize, count)
	err := item.Offset(paginate.Offset).Limit(paginate.Limit).Find(&data).Error
	if err != nil {
		panic(err)
	}
	return data, &paginate
}

func GetNewSpreadResultEnterpriseList(page int, pageSize int, c *gin.Context) ([]*SpreadResult, *Paginator) {
	var data []*SpreadResult
	item := DB.Table("spread as t1").Select("t1.id, t1.title,t1.type, t2.name as user_name, t3.account, t1.cover, t1.maibao_num, t1.maibao_spend_num, t1.content, t1.status, t1.created_at, t1.province_id as province, t1.maibao_num_surplus / t1.maibao_spend_num as share_num").Joins("LEFT JOIN enterprise AS t2 ON t1.user_id = t2.id").Joins("LEFT JOIN enterprise_users AS t3 ON t1.user_id = t3.enterprise_id ").Where("t1.is_deleted=0").Where("t1.status<>4").Where("t1.type=1").Order("created_at desc")

	if name := c.Query("name"); name != "" {
		item.Where("t2.name like ? or t3.phone like", "%"+name+"%", "%"+name+"%")
	}

	if title := c.Query("title"); title != "" {
		item = item.Where("t1.title like ? ", "%"+title+"%")
	}
	if begin_time := c.Query("begin_time"); begin_time != "" {
		item = item.Where("t1.created_at > ?", begin_time)
	}
	if end_time := c.Query("end_time"); end_time != "" {
		item = item.Where("t1.created_at < ?", end_time)
	}
	var count int
	item.Count(&count)
	paginate := NewPage(page, pageSize, count)
	err := item.Offset(paginate.Offset).Limit(paginate.Limit).Find(&data).Error
	if err != nil {
		panic(err)
	}
	return data, &paginate
}

func GetSpreadResultMemberById(id int) (*SpreadResult, error) {
	var data SpreadResult
	err := DB.Table("spread as t1").Select("t1.id, t1.title, t2.user_name, t2.mobile_phone as account, t1.cover, t1.maibao_num, t1.content, t1.maibao_spend_num, t1.status, t1.created_at, t3.name as province, t1.maibao_num_surplus / t1.maibao_spend_num as share_num, t2.id as card_id, t2.head_picture as card_head_picture").Joins("left join cards as t2 on t1.user_id = t2.user_id").Joins("left join places as t3 on  t1.province_id = t3.id").Where("t1.id=?", id).Find(&data).Error
	if err != nil {
		return nil, err
	}
	return &data, nil
}

func GetSpreadResultEnterpriseById(id int) (*SpreadResult, error)  {
	var data SpreadResult
	err := DB.Table("spread as t1").Select("t1.id, t1.title,t1.type, t2.name as company, t4.name as user_name, t3.account, t1.cover, t1.maibao_num, t1.maibao_spend_num, t1.content, t1.status, t1.created_at, t1.province_id as province, t1.maibao_num_surplus / t1.maibao_spend_num as share_num").Joins("LEFT JOIN enterprise AS t2 ON t1.user_id = t2.id").Joins("LEFT JOIN enterprise_users AS t3 ON t1.user_id = t3.enterprise_id ").Joins("LEFT JOIN enterprise_staff as t4 on t3.staff_id = t4.id").Where("t1.is_deleted=0").Where("t1.status<>4").Where("t1.type=1").Where("t1.id=?", id).Order("created_at desc").Find(&data).Error
	if err != nil {
		return nil, err
	}
	return &data, nil
}
// 审核
func UpdateSpreadById(id int, status int, remarks string) (error) {
	err := DB.Table("spread").Where("id=?", id).Updates(map[string]interface{}{"status": status, "remarks": remarks}).Error
	if err != nil {
		return err
	}
	return nil
}

// 删除
func DelSpreadById(id int) (error) {
	err := DB.Table("spread").Where("id=?", id).Update("is_deleted", 1).Error
	if err != nil {
		return err
	}
	return nil
}

// 退还脉宝
func RefundMaiBao(id int, msg string) (error) {
	var spread struct {
		Code             string `json:"code"`
		MaibaoNumSurplus int    `json:"maibao_num_surplus"`
		UserId           int    `json:"user_id"`
		Title            string `json:"title"`
	}
	err := DB.Table("spread").Select("code, maibao_num_surplus, user_id, title").Where("id=?", id).First(&spread).Error
	if err != nil {
		return err
	}
	var users struct {
		Maibao float32 `json:"maibao"`
	}
	//db := DB.Begin()
	// todo 查找用户脉宝数
	errUser := DB.Table("users").Select("maibao").Where("id=?", spread.UserId).First(&users).Error
	if errUser != nil {
		//db.Rollback()
		return nil
	}
	maibao := spread.MaibaoNumSurplus + int(users.Maibao)
	//todo 添加用户脉宝
	userErr := DB.Table("users").Where("id=?", spread.UserId).Updates(map[string]interface{}{"maibao": maibao}).Error
	if userErr != nil {
		//db.Rollback()
		return userErr
	}
	num := strconv.Itoa(spread.MaibaoNumSurplus)
	// todo 添加脉宝退还记录
	maibao_bill := MaiBaoBill{
		UserId:    spread.UserId,
		Type:      1,
		Title:     msg + spread.Title + "退还金额" + num + "个",
		Amount:    float32(spread.MaibaoNumSurplus),
		Cate:      1,
		CreatedAt: time.Now(),
	}
	maibao_bill_id, maibao_billErr := maibao_bill.Add()
	if maibao_billErr != nil {
		//db.Rollback()
		return maibao_billErr
	}
	// todo 还记录详情

	maibao_bill_extend := MaiBaoBillExtend{
		UserId:    spread.UserId,
		Type:      2,
		BillId:    maibao_bill_id,
		CreatedAt: time.Now(),
	}
	maibao_bill_extendErr := maibao_bill_extend.Add()
	if maibao_bill_extendErr != nil {
		//db.Rollback()
		return maibao_bill_extendErr
	}
	// todo redis 删除w
	err1 := DelRedisCodeKey(spread.Code)
	if err1 != nil {
		//db.Rollback()
		return err1
	}
	// 清空脉宝剩余个数
	numErr := DelSpreadByCodeMaibaoNumSurplus(spread.Code)
	if numErr != nil {
		//db.Rollback()
		return err1
	}
	//db.Commit()

	return nil
}

// 删除code redis
func DelRedisCodeKey(code string) error {
	conn := gredis.RedisConn.Get()
	defer conn.Close()

	_, err := conn.Do("select", 1)

	if err != nil {
		return err
	}
	_, err = conn.Do("del", code)
	if err != nil {
		return err
	}
	return nil

}

// 通过code 清空剩余个数
func DelSpreadByCodeMaibaoNumSurplus(code string) error {
	err := DB.Table("spread").Where("code=?", code).Update("maibao_num_surplus", 0).Error
	if err != nil {
		return err
	}
	return nil
}
